package com.mls.guardian.appst.service;

import com.mls.guardian.appst.AppController;
import com.mls.guardian.appst.common.Jps;
import com.mls.guardian.common.RemoteUtil;
import com.mls.guardian.config.AppSTConfig;
import com.mls.guardian.config.ProjectConfig;
import com.mls.guardian.config.VersionConfig;
import com.mls.guardian.dataobj.FileObj;
import com.mls.guardian.dataobj.ProcessMessage;
import com.mls.guardian.dataobj.ServerProcessInfo;
import com.mls.guardian.em.ContainerRole;
import com.mls.guardian.em.FileType;
import com.mls.guardian.em.ModuleType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * Created by jl on 15/11/25.
 */
public class ProjectService {
    private static final Logger log = LoggerFactory.getLogger(ProjectService.class);

    private AppController appController;
    private AppSTConfig appSTConfig;
    private List<ProjectConfig> projectObjList = new ArrayList();


    public ProjectService(AppController appController, AppSTConfig appSTConfig) {
        this.appController = appController;
        this.appSTConfig = appSTConfig;
    }

    public void init(List<ProjectConfig> projectObjList) {
        this.projectObjList = projectObjList;
    }


    public ProjectConfig getProjectByAppName(String projectName) {
        ProjectConfig projectConfig = null;

        for (ProjectConfig projectConfigTemp : projectObjList) {
            if (projectConfigTemp.getProjectName().equals(projectName)) {
                projectConfig = projectConfigTemp;
                break;
            }
        }

        return projectConfig;
    }


    public ServerProcessInfo getProjectAndStatus(String projectName, ContainerRole role) throws Exception {
        ServerProcessInfo projectAndStatusInfo = new ServerProcessInfo();
        projectAndStatusInfo.setIp(RemoteUtil.getLocalHostIP());
        projectAndStatusInfo.setVersion(VersionConfig.getVersion());
        projectAndStatusInfo.setRole(role);
        List<ProcessMessage> allProcessObjList = new ArrayList<ProcessMessage>();

        ProjectConfig projectConfig = getProjectByAppName(projectName);

        if (projectConfig == null) {
            return projectAndStatusInfo;
        }

        List<ProcessMessage> processMessages = Jps.getProcess(projectName);

        List<String> jarAppList = projectConfig.getJarModuleList();
        if (jarAppList != null) {
            for (String appName : jarAppList) {
                ProcessMessage processMessage = new ProcessMessage("0", appName, ModuleType.JAR, false);
                for (ProcessMessage processRun : processMessages) {
                    if (processRun.getModuleName().equals(appName)) {
                        processMessage.setProcessId(processRun.getProcessId());
                        processMessage.setRun(true);
                    }
                }

                allProcessObjList.add(processMessage);
            }
        }


        List<String> webAppList = projectConfig.getWebModuleList();

        if (webAppList != null) {
            for (String appName : webAppList) {
                ProcessMessage processMessage = new ProcessMessage("0", appName, ModuleType.WEB, false);
                for (ProcessMessage processRun : processMessages) {
                    if (processRun.getModuleName().equals(appName)) {
                        processMessage.setProcessId(processRun.getProcessId());
                        processMessage.setRun(true);
                    }
                }

                allProcessObjList.add(processMessage);
            }
        }


        projectAndStatusInfo.setProcessList(allProcessObjList);

        return projectAndStatusInfo;
    }

    /**
     * 获取指定目录下面的子文件
     *
     * @param projectName WMS
     * @param moduleName  BaseComServer
     * @param parent      a/b/c
     * @return
     */
    public List<FileObj> getFileInfo(String projectName, String moduleName, String... parent) throws Exception {
        List<FileObj> list = new ArrayList<FileObj>();
        Optional<ProjectConfig> projectConfigOptional = this.projectObjList.stream().filter(t -> t.getProjectName().equals(projectName)).findFirst();
        if (projectConfigOptional.isPresent()) {
            ProjectConfig projectConfig = projectConfigOptional.get();
            int index = projectConfig.getWebModuleList().indexOf(moduleName);
            if (index > -1) {
                //web模块映射目录
                String realName = projectConfig.getWebAliasList().get(index);
                Path fullPath = Paths.get(this.appSTConfig.getMoveDest(), projectName, realName);
                Path parentPath = Paths.get("");
                if (parent != null && parent.length > 0) {
                    for (String item : parent) {
                        if (item != null && item.trim().length() > 0) {
                            parentPath = Paths.get(parentPath.toString(), item);
                        }
                    }
                    fullPath = Paths.get(fullPath.toString(), parentPath.toString());
                }

                //获取子目录
                List<String> suffixNameList = new ArrayList<String>();
                suffixNameList.add("js");
                suffixNameList.add("css");
                suffixNameList.add("htm");
                suffixNameList.add("html");
                suffixNameList.add("xml");
                suffixNameList.add("json");

                log.info("----遍历目录[{}]----", fullPath.toString());
                File pFile = new File(fullPath.toString());
                if (pFile != null && pFile.isDirectory()) {
                    for (File item : pFile.listFiles(new FilenameFilter() {
                        @Override
                        public boolean accept(File dir, String name) {
                            String[] array = name.split("\\.");
                            if (array == null || array.length == 1) {
                                //文件夹
                                return true;
                            } else if (array != null && array.length >= 2 && array[1].length() > 0) {
                                //指定类型文件
                                if (suffixNameList.contains(array[1].toLowerCase())) {
                                    return true;
                                }
                            }
                            return false;
                        }
                    })) {
                        String filePath = Paths.get(parentPath.toString(), item.getName()).toString();
                        list.add(new FileObj(item.getName(), filePath, item.isDirectory() ? FileType.FOLDER : FileType.FILE));
                    }
                }
            } else {
                log.info("----模块未找到[{}]----", moduleName);
            }
        } else {
            log.info("----项目未找到[{}]----", projectName);
        }

        return list;
    }

    public String getUpgradeVersion() {
        return VersionConfig.getVersion();

    }
}
